#include <cassert>
#include "../include/Tetris.hpp"
#include "../include/Color.hpp"
#include "../include/Blocks.hpp"

Tetris::Tetris(int argc,char* argv[])
{
    char* pos = strrchr(argv[0],'/');
    if(pos != nullptr)
    {
        *++pos = '\0';
        build_path = argv[0];
    }
    InitWindow(500,620,"Tetris");//初始化窗口，参数分别是宽度，高度，标题
    SetTargetFPS(60);//设置帧率
    //LoadFont()将字体从文件加载到CPU内存
    //参数分别为文件名、字体大小、NULL，0表示默认字符集
    font = Font(LoadFontEx((build_path + "fonts" + "/BebasNeue-Regular.ttf").c_str(),64,nullptr,0));
    const bool GameInit = game.Initialize(build_path);
    assert(GameInit);
}

bool Tetris::EventTrigger(float interval)
{
    float currentTime = GetTime();//获取当前时间
    if(currentTime - lastUpdateTime >= interval)
    {
        lastUpdateTime = currentTime;
        return true;
    }

    return false;
}

void Tetris::run()
{
    //WindowShouldClose用于检查是否按下了KEY_ESCAPE或关闭图标
    while(WindowShouldClose() == false)
    {
        UpdateMusicStream(game.music);//更新音乐流的缓冲区
        
        game.HandleInput();
        if(EventTrigger(0.2))//0.2秒，方块往下走一步
        {
            game.MoveBlockDown();
        }
        
        //开始绘制新的一帧  
        BeginDrawing();  
        //清除背景色  
        ClearBackground(black);  

        //用于绘制文本，参数分别为字体、文本、位置、大小、间距、颜色
        DrawTextEx(font,"score",{365,15},38,2,WHITE);
        DrawTextEx(font,"Next",{365,175},38,2,WHITE);

        if(game.GameOver)//游戏结束，绘制分数
        {
            DrawTextEx(font,"GAME OVER",{345,450},40,2,WHITE);
        }
        //参数分别为{x,y,width,heigh},float圆度，越大越圆，int，颜色
        //grid绘制的时候，11 + 10 * 30 = 310，所以这里的x轴设置为320
        //宽度要在分数的字体下面，55即可
        DrawRectangleRounded({320,55,170,60},0.3,6,darkGrey);//绘制圆角Rectangle

        //这行代码调用MeasureTextEx函数计算scoreText字符串在指定字体和大小下的尺寸（宽度和高度），结果存储在textSize变量中。
        //font是字体参数
        //scoreText是要测量的文本
        //38是字体大小
        //2是间距
        std::string score = std::to_string(game.score);
        Vector2 TextSize = MeasureTextEx(font,score.c_str(),38,2);

        DrawTextEx(font,score.c_str(),{320 + (170 - TextSize.x) / 2,65},38,2,WHITE);

        //存下一个方块
        DrawRectangleRounded({320,215,170,180},0.3,6,darkGrey);

        game.Draw();

        //结束绘制，并显示这一帧  
        EndDrawing();  
    }
}

Tetris::~Tetris()
{
    UnloadFont(font);//卸载字符集
    CloseWindow();//关闭窗口
}

